package database

import (
	"blog/config"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"sync"
)

var (
	dbOnce   sync.Once
	dbClient *gorm.DB
)

func GetDB() *gorm.DB {
	dbOnce.Do(func() {
		cfg := config.GetConfig()
		var err error
		dbClient, err = NewPostgresDB(&cfg.Database)
		if err != nil {
			panic(err)
		}
	})
	return dbClient
}

func NewPostgresDB(cfg *config.Database) (*gorm.DB, error) {

	db, err := gorm.Open(postgres.Open(cfg.DSN), &gorm.Config{
		PrepareStmt: true,
	})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(cfg.MaxLifetime)
	return db, nil
}
